//
//  YWDetailNoticeViewController.m
//  maintain
//
//  Created by 郑想 on 16/7/19.
//  Copyright © 2016年 ewin. All rights reserved.
//
#import "UIView+Extension.h"
#import "YWConst.h"
#import <QuickLook/QuickLook.h>
#import "UIColor+CustomColors.h"
#import "YWMacro.h"
#import "YWKeepWatchMissionManager.h"
#import "UIImageView+WebCache.h"
#import "GropPictureView.h"
#import "YWGropButtonView.h"
#import "YWNotice.h"
#import "YWNoticeManager.h"
#import "YWCommonTool.h"
#import "YWHandler.h"
#import "YWAttachmentManager.h"
#import "YWLoginTool.h"
#import "YWLoginUser.h"

#import "YWResourceManager.h"
#import "YWReply.h"
#import "YWReplyManager.h"
#import "YWDetailNoticeViewController.h"
//#import "YWAlertView.h"
#import "YWNewCommentCell.h"
#import "YWNoticeAndTempMissionCell.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "MBProgressHUD.h"
#import "FTPopOverMenu.h"
#import "YWModifyNoticeTableViewController.h"
#import "YWSelectContactTableViewController.h"
#import "YWContactManager.h"
#import "YWSelectAtUserTableViewController.h"

@interface YWDetailNoticeViewController ()<UITableViewDelegate, UITableViewDataSource,YWNoticeAndTempMissionCellDelegate,YWSelectAtUserTableViewDelegate,YWContactVCSelectContactDelegate,UITextFieldDelegate,QLPreviewControllerDataSource>
@property (nonatomic, strong) NSArray<YWReply *>* replyArray;
@property (nonatomic, strong) YWattachment *attachment;
@property (nonatomic, copy) NSString* content;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, assign) NSInteger showAlertCount;
/** 回复栏 */
@property (nonatomic, strong) UIView *replyView;
@property (nonatomic, strong) YWHandler *atUser;
@property (nonatomic, strong) UIButton * selectButton;
@property (nonatomic, strong) UITextField * textField;
@property (nonatomic, strong) UIView * line2;
@property (nonatomic, weak) MBProgressHUD* HUD;
@end

@implementation YWDetailNoticeViewController

- (void)viewDidLoad{
    [super viewDidLoad];
    self.title = NSLocalizedString(@"detailOfNotice", nil);//@"通知详情";
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor customBackgroudColor];
    
    if (self.notice.fromUser.uniqueId == [YWLoginTool loginUser].uniqueId) {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"• • • " style:UIBarButtonItemStylePlain target:self action:@selector(clickRightBarButtonEvent:event:)];
    }
    
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.replyView];
    
    _showAlertCount = 0;
    [self setupOnceNotifications];
    //请求评论
    [[YWReplyManager shareManager] requestReplysWithRelationId:@(self.notice.noticeId).stringValue type:YWReplyRelationTypeNotice WithComplete:^(BOOL success) {
        [self.tableView reloadData];
    }];
}

#pragma mark - datasource
- (NSArray *)replyArray{
    if (!_replyArray) {
        NSArray *commentArray = [[YWReplyManager alloc] replysWithtRelationId:_notice.noticeId andRelationType:YWReplyRelationTypeNotice];
        _replyArray = commentArray;
    }
    return _replyArray;
}

-(UITableView *)tableView{
    if (!_tableView) {
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH,SCREEN_HEIGHT - 64 - 46) style:UITableViewStylePlain];
        tableView.tableFooterView = [[UIView alloc] init];
        
        tableView.backgroundColor = [UIColor customBackgroudColor];
        tableView.separatorColor = [UIColor customLineColor];
        tableView.allowsSelection = NO;
        
        tableView.delegate = self;
        tableView.dataSource = self;
        
        [tableView registerClass:[YWNoticeAndTempMissionCell class] forCellReuseIdentifier:YWNoticeAndTempMissionCellIdentifier];
        [tableView registerClass:[YWNewCommentCell class] forCellReuseIdentifier:YWNewCommentCellIdetifer];
        tableView.estimatedRowHeight = 250.0f;
        tableView.rowHeight = UITableViewAutomaticDimension;
        
        _tableView = tableView;
    }
    return _tableView;
}
- (UIView *)replyView{
    if (!_replyView) {
        _replyView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT-64-46, SCREEN_WIDTH, 46)];
        _replyView.backgroundColor = [UIColor whiteColor];
        
        UIView *line1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 1)];
        line1.backgroundColor = [UIColor customLineColor];
        [_replyView addSubview:line1];
        [self setReplyViewLayout];
    }
    return _replyView;
}

- (void)setReplyViewLayout{
    self.textField = [[UITextField alloc] initWithFrame:CGRectMake(kButtonW, 0, SCREEN_WIDTH-kButtonW-15, 40)];
    self.textField.placeholder = NSLocalizedString(@"reply", nil);//@"回复";
    self.textField.font = kContentFont;
    self.textField.returnKeyType = UIReturnKeySend;
    self.line2 = [[UIView alloc] initWithFrame:CGRectMake(self.textField.x, CGRectGetMaxY(self.textField.frame), self.textField.width, 1)];
    self.line2.backgroundColor = [UIColor customBlueColor];
    
    [_replyView addSubview:self.textField];
    [_replyView addSubview:self.line2];
    self.textField.delegate = self;
    self.selectButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.selectButton.frame = CGRectMake(0, 0, kButtonW, kButtonH);
    [self.selectButton addTarget:self action:@selector(handleSelectButtonToPeople:) forControlEvents:UIControlEventTouchUpInside];
    [_replyView addSubview:self.selectButton];
    [self.selectButton setTitle:@"@" forState:UIControlStateNormal];
    self.selectButton.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    [self.selectButton setTitleColor:[UIColor customTextGrayColor] forState:UIControlStateNormal];
}

- (void)handleSelectButtonToPeople:(UIButton *)sende{
    if (self.notice.receiverIds.length>0) {
        YWSelectAtUserTableViewController * selectAtUserVC = [[YWSelectAtUserTableViewController alloc] init];
        selectAtUserVC.delegate = self;
        NSMutableArray *allUser = [NSMutableArray array];
        if (self.notice.fromUser) {
            [allUser addObject:self.notice.fromUser];
        }
        NSArray *handlers = [[YWContactManager shareManager] handlerWithDepartmentIds:self.notice.receiverIds];
        [allUser addObjectsFromArray:handlers];
        selectAtUserVC.allUserArray = allUser;
        [self.navigationController pushViewController:selectAtUserVC animated:YES];
    }else if (self.notice.organizationNos.length>0) {
        YWSelectContactTableViewController * selectContactVC = [[YWSelectContactTableViewController alloc] init];
        selectContactVC.delegate = self;
        selectContactVC.isMultiSelect = NO;
        selectContactVC.ownContacts = self.atUser ? @[self.atUser] :nil;
        selectContactVC.titleName = [NSString stringWithFormat:@"%@@人",NSLocalizedString(@"select", nil)];
        [self.navigationController pushViewController:selectContactVC animated:YES];
    }
}

- (void)selectSingleContact:(YWHandler *)contact{
    [self selectAtUser:contact];
}

- (void)selectAtUser:(YWHandler *)contact{
    if (contact) {
        self.atUser = contact;
        NSString * atButtonTitle = [NSString stringWithFormat:@"@%@",self.atUser.userName.length?self.atUser.userName:@""];
        CGSize size =[atButtonTitle sizeWithAttributes:@{NSFontAttributeName:KTitleFont}];
        CGSize standernSize = [[NSString stringWithFormat:@"四个中文字"] sizeWithAttributes:@{NSFontAttributeName:KTitleFont}];
        CGFloat width = size.width>standernSize.width ? standernSize.width : size.width;
        width = width + 6;//＋6是让前后有留白，不会紧贴屏幕
        self.selectButton.frame = CGRectMake(0, 0, width, kButtonH);
        self.textField.frame = CGRectMake(width, 0, SCREEN_WIDTH-width-15, kButtonH);
        self.line2.frame = CGRectMake(width, CGRectGetMaxY(self.textField.frame), self.textField.width, 1);
        
        self.selectButton.titleLabel.font = KTitleFont;
        [self.selectButton setTitleColor:[UIColor customBlueColor] forState:UIControlStateNormal];
        [self.selectButton setTitle:atButtonTitle forState:UIControlStateNormal];
    }else{
        [self whenAtUserIsNilReSetFrame];
    }
}

- (void)whenAtUserIsNilReSetFrame{
    self.atUser = nil;
    self.textField.text = nil;
    self.textField.frame = CGRectMake(kButtonW, 0, SCREEN_WIDTH-kButtonW-15, kButtonH);
    self.line2.frame = CGRectMake(self.textField.x, CGRectGetMaxY(self.textField.frame), self.textField.width, 1);
    self.selectButton.frame = CGRectMake(0, 0, kButtonW, kButtonH);
    [self.selectButton setTitle:@"@" forState:UIControlStateNormal];
    self.selectButton.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    [self.selectButton setTitleColor:[UIColor customTextGrayColor] forState:UIControlStateNormal];
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    if (textField.text.length==0) {
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"writeReplyContent", nil)];
        return NO;
    }else if (textField.text.length > 100){
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"replyContentLengthCannotMoreThan100", nil)];
        return NO;
    }else if ([YWCommonTool isContainsEmoji:textField.text]){
        [YWCommonTool showTextHUDWithContent:NSLocalizedString(kTextCantContainEmoji, nil)];
        return NO;
    }
    _content = textField.text;
    NSString *url = [YWCommonTool postReplyUrl];
    [[YWReplyManager shareManager] commitReplys:[self createReply] url:url WithComplete:^(BOOL success) {
        if (success) {
            [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"replySucceed", nil)];
            //回复成功后，要回复原样
            [self whenAtUserIsNilReSetFrame];
            _replyArray = nil;
            [self.tableView reloadData];
        }
    }];
    [textField endEditing:YES];
    return YES;
}

-(YWReply *)createReply{
    YWReply *reply = [[YWReply alloc]init];
    reply.replyId = 0;//提交成功后id会被服务端返回的id替换
    reply.relationId = _notice.noticeId;
    reply.relationType = YWReplyRelationTypeNotice;
    reply.content = _content;
    reply.atUser = _atUser;
    YWHandler *replier = [[YWHandler alloc] init];
    replier.uniqueId = [YWLoginTool loginUser].uniqueId;
    reply.replier = replier;
    reply.replyTime = [[NSDate date] timeIntervalSince1970]*1000;
    reply.isRead = YES;
    return reply;
}

#pragma mark - UITableViewDelegate
//-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    if (indexPath.section==0) {
//        return [tableView fd_heightForCellWithIdentifier:YWNoticeAndTempMissionCellIdentifier cacheByIndexPath:indexPath configuration:^(YWNoticeAndTempMissionCell *cell) {
//            [self configureNewNoticeCell:cell atIndexPath:indexPath];
//        }];
//    }else{
//        return [tableView fd_heightForCellWithIdentifier:YWNewCommentCellIdetifer cacheByIndexPath:indexPath configuration:^(YWNewCommentCell *cell) {
//            [self configureCommentCell:cell atIndexPath:indexPath];
//        }];
//    }
//}

- (void)configureNewNoticeCell:(YWNoticeAndTempMissionCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    cell.fd_enforceFrameLayout = NO;
    cell.showExpendBtn = NO;
    //详情中不显示 请于...完成
    [[cell viewWithTag:101] removeFromSuperview];
    //详情中不显示 有几条评论
    [[cell viewWithTag:102] removeFromSuperview];
    cell.notice = _notice;
    cell.delegate = self;
}

- (void)configureCommentCell:(YWNewCommentCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    cell.fd_enforceFrameLayout = NO;
    YWReply *reply = self.replyArray[indexPath.row];
    cell.reply = reply;
    //除了第一条评论则隐藏最左边评论图标
    [cell viewWithTag:101 ].hidden = indexPath.row == 0 ? NO : YES;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return section == 0 ? 0:1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0;
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 0) {
        return 1;
    }  else {
        return self.replyArray.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        YWNoticeAndTempMissionCell *cell = [tableView dequeueReusableCellWithIdentifier:YWNoticeAndTempMissionCellIdentifier];
        [self configureNewNoticeCell:cell atIndexPath:indexPath];
        return cell;
    } else {
        YWNewCommentCell *cell = [tableView dequeueReusableCellWithIdentifier:YWNewCommentCellIdetifer];
        [self configureCommentCell:cell atIndexPath:indexPath];
        return cell;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.view endEditing:YES];
}

#pragma mark - YWNoticeNewCellDelegate
-(void)handleExpandButton:(UITableViewCell *)cell{
    NSIndexPath* indexPath = [self.tableView indexPathForCell:(YWNoticeAndTempMissionCell*)cell];
    YWNotice *notice = self.notice;
    notice.isExpand = notice.isExpand ? NO : YES;
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationFade];
}

-(void)showAttachment:(YWattachment *)attachment{
    _attachment = attachment;
    if (_attachment.localName) {
        QLPreviewController *previewer = [[QLPreviewController alloc] init];
        [previewer setDataSource:self];
        [previewer setCurrentPreviewItemIndex:0];
        [self.navigationController pushViewController:previewer animated:YES];
    }
}

#pragma mark -QLPreviewControllerDataSource
- (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller{
    return 1;
}

-(id<QLPreviewItem>)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index{
    NSString *path = [[YWResourceManager shareManager] fileCachePathFromResourcePath:_attachment.localName];
    NSURL *url = [NSURL fileURLWithPath:path];
    return url;
}

- (void)modifyNotice:(id)sender{
    self.notice = [[YWNoticeManager shareManager] noticeWithNoticeId:self.notice.noticeId];
    [self.tableView reloadData];
}

- (void)reflashNoticeAttachmentReflash:(NSNotification*)noti{
    [self.tableView reloadData];
    _showAlertCount++;
    if (_showAlertCount == 1 && [noti.object isKindOfClass:[YWattachment class]]) {
        YWattachment *attachment = (YWattachment *)noti.object;
        NSString *fileName = attachment.attachmentName.length>0?attachment.attachmentName:NSLocalizedString(@"noTitle", nil);
        NSString *fileStr = [NSString stringWithFormat:@"%@:%@",NSLocalizedString(@"downloadFinishedAndOpen", nil),fileName];
        UIAlertController* alertController= [UIAlertController alertControllerWithTitle:NSLocalizedString(@"tips", nil) message:fileStr preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            _showAlertCount = 0;
        }]];
        [alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self showAttachment:attachment];
            _showAlertCount = 0;
        }]];
        [self presentViewController:alertController animated:YES completion:nil];
    }
}

#pragma mark ----- 有关键盘
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.replyView.hidden = NO;
    [self setUpNotification];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.textField endEditing:YES];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:KPostNoticeAttachmentReflashNotification object:nil];
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    self.replyView.hidden = YES;
}

#pragma mark - notification
- (void)setupOnceNotifications{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(modifyNotice:) name:KRefreshModifyYWNoticeNotification object:nil];
}
- (void)setUpNotification{
    //    键盘show
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    //    键盘hide
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reflashNoticeAttachmentReflash:) name:KPostNoticeAttachmentReflashNotification object:nil];
}

- (void)keyboardWillShow:(NSNotification *)info{
    //键盘高度
    CGFloat kbHeight = [[info.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    // 取得键盘的动画时间
    CGFloat duration = [[info.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    
    [UIView animateWithDuration:duration animations:^{
        _replyView.y = SCREEN_HEIGHT -64 - 46 - kbHeight;
    }];
}

- (void)keyboardWillHide:(NSNotification *)info{
    double duration = [[info.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView animateWithDuration:duration animations:^{
        _replyView.y = SCREEN_HEIGHT - 64 - 46;
    }];
}


- (void)clickRightBarButtonEvent:(UIBarButtonItem *)sender event:(UIEvent *)event{
    [FTPopOverMenu showFromEvent:event
    withMenu:@[NSLocalizedString(@"modify", nil),NSLocalizedString(@"delete", nil)]imageNameArray:@[@"menu_edit",@"menu_delete"] doneBlock:^(NSInteger selectedIndex) {
        if (selectedIndex == 0) {
            [self pushToModify];
        }else if (selectedIndex ==1){
            [self deleteNotice];
    }
    } dismissBlock:nil];
}

- (void)pushToModify{
    YWModifyNoticeTableViewController * modifyNotiVC = [[YWModifyNoticeTableViewController alloc] init];
    modifyNotiVC.notice = self.notice;
    [self.navigationController pushViewController:modifyNotiVC animated:YES];
}

- (void)deleteNotice{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"makeSureToDelete", nil) message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"cancel", nil) style:UIAlertActionStyleCancel handler:nil]];
    YWWeakSelf(weakSelf);
    [alert addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf.HUD show:YES];
        [[YWNoticeManager shareManager] requestDeleteNotice:weakSelf.notice.noticeId complete:^(BOOL success) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.HUD hide:YES];
                if (success) {
                    [YWCommonTool showTextHUDWithContent:NSLocalizedString(@"deleteSucceed", nil)];
                    [weakSelf.navigationController popViewControllerAnimated:YES];
                }
            });
        }];
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (MBProgressHUD*)HUD
{
    if (!_HUD) {
        MBProgressHUD* hud = [[MBProgressHUD alloc] initWithView:[UIApplication sharedApplication].keyWindow];
        hud.labelFont = kHUDLabelFont;
        hud.labelText = NSLocalizedString(kTextBeingProcessed, nil);
        hud.dimBackground = YES;
        //hud.animationType = MBProgressHUDAnimationZoom;
        _HUD = hud;
        _HUD.tag = kMBProgressHUDTag;
        [self.navigationController.view addSubview:hud];
    }
    return _HUD;
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
